package com.aioething.iot.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.aioething.iot.beans.ActionRequest;
import com.aioething.iot.beans.RegisterRequest;
import com.aioething.iot.beans.RegisterResponse;
import com.aioething.iot.dto.EquipmentDto;
import com.aioething.iot.model.Equipment;
import com.aioething.iot.service.IEmqxService;
import com.aioething.iot.service.IEquipmentService;
import com.aioething.iot.vo.EquipmentVo;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("equipment")
public class EquipmentController {
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IEmqxService emqxService;

    @PutMapping()
    public int save(@RequestBody Equipment equipment) {
        equipment.setPsk(IdUtil.fastSimpleUUID());
        equipment.setCreateTime(new Date());
        return equipmentService.save(equipment);
    }

    @DeleteMapping
    public int delete(@RequestParam String equipmentId) {
        return equipmentService.delete(equipmentId);
    }

    @PostMapping()
    public int update(@RequestBody Equipment equipment) {
        return equipmentService.update(equipment);
    }

    @GetMapping()
    public PageInfo<EquipmentVo> query(EquipmentDto equipmentDto) {
        return equipmentService.query(equipmentDto);
    }

    @PostMapping("register")
    public RegisterResponse register(@RequestBody RegisterRequest request) {
        return equipmentService.register(request);
    }

    @PostMapping("callAction")
    public JSONObject callAction(@RequestBody ActionRequest request) throws IOException {
        JSONObject obj = emqxService.actionCall(String.format("things/%s/%s/action/down", request.getProductId(), request.getDeviceName()), request.getMethod(), request.getEquipmentId(), request.getParams());
        Integer code = obj.getInt("code", -1);
        if (code != 0) {
            throw new InternalException(String.format("调用失败(%d)", code));
        }
        return obj;
    }
}
